﻿using huqiang.Core.HGUI;
using huqiang.Core.UIData;
using huqiang.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace huqiang.UIComposite
{
    public class GridLayout : Composite
    {
        /// <summary>
        /// 项目尺寸
        /// </summary>
        public Vector2 ItemSize = new Vector2(1, 1);
        Vector2 _aSize;
        public Vector2 ActualItemSize { get => _aSize; }
        protected FakeStruct modData;
        int _row;
        int _col;
        public int Row { get => _row; }
        public int Column { get => _col; }
        /// <summary>
        /// 项目模板
        /// </summary>
        public FakeStruct ItemMod
        {
            set
            {
                modData = value;
                if (modData != null)
                {
                    ItemSize = UIAdaptive.GetSize(Enity, modData);
                }
                Clear();
            }
            get { return modData; }
        }
        IList dataList;
        Array array;
        FakeArray fakeStruct;
        /// <summary>
        /// 传入类型为IList
        /// </summary>
        public object BindingData
        {
            get
            {
                if (dataList != null)
                    return dataList;
                if (array != null)
                    return array;
                return fakeStruct;
            }
            set
            {
                if (value is IList)
                {
                    dataList = value as IList;
                    array = null;
                    fakeStruct = null;
                }
                else if (value is Array)
                {
                    dataList = null;
                    array = value as Array;
                    fakeStruct = null;
                }
                else if (value is FakeArray)
                {
                    dataList = null;
                    array = null;
                    fakeStruct = value as FakeArray;
                }
                else
                {
                    dataList = null;
                    array = null;
                    fakeStruct = null;
                }
            }
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="index">数据索引</param>
        /// <returns></returns>
        public object GetData(int index)
        {
            if (index < 0)
                return null;
            if (dataList != null)
            {
                if (index >= dataList.Count)
                    return null;
                return dataList[index];
            }
            if (array != null)
            {
                if (index >= array.Length)
                    return null;
                return array.GetValue(index);
            }
            return null;
        }
        int m_len;
        /// <summary>
        /// 数据长度
        /// </summary>
        public int DataLength
        {
            set { m_len = value; }
            get
            {
                if (dataList != null)
                    return dataList.Count;
                if (array != null)
                    return array.Length;
                if (fakeStruct != null)
                    return fakeStruct.Length;
                return m_len;
            }
        }
        /// <summary>
        /// UI项目列表
        /// </summary>
        public List<ScrollItem> Items = new List<ScrollItem>();
        /// <summary>
        /// 清除UI资源
        /// </summary>
        public void Clear()
        {
            
        }
        public bool AutoSize;
        /// <summary>
        /// 设置项目模型
        /// </summary>
        /// <param name="name">模型名称</param>
        public void SetItemMod(string name)
        {
            if (BufferData == null)
                return;
            var mod = HGUIManager.FindChild(BufferData, name);
            if (mod != null)
            {
                ItemSize = UIElementLoader.GetSize(mod);
            }
            ItemMod = mod;
        }
        public override void Initial(FakeStruct mod, UIElement element, UIInitializer initializer)
        {
            base.Initial(mod, element, initializer);
            SetItemMod("Item");
            HGUIManager.RecycleChild(Enity);
            Enity.SizeChanged = (o) => { Refresh(); };
        }
        /// <summary>
        /// 刷新到默认位置
        /// </summary>
        public void Refresh()
        {
            if (ItemMod == null)
                return;
            _col = 0;
            if (ItemSize.x > 0)
                _col = (int)(Enity.m_sizeDelta.x / ItemSize.x);
            if (_col < 1)
                _col = 1;
            int len = DataLength;
            _row = len / _col;
            if (len % _col > 0)
                _row++;
            _aSize.x = Enity.m_sizeDelta.x / _col;
            float r = _aSize.x / ItemSize.x;
            _aSize.y = ItemSize.y * r;
            if (AutoSize)
                Enity.m_sizeDelta.y = _row * _aSize.y;
            float left = Enity.m_sizeDelta.x * (Enity.Pivot.x - 1);
            float top = Enity.m_sizeDelta.y *(1- Enity.Pivot.y);
            var pivot = UIElementLoader.GetPivot(ItemMod);
            float ox = _aSize.x * (1 - pivot.x);
            float oy = _aSize.y * (pivot.y - 1);
            for (int i = 0; i < DataLength; i++)
            {
                int col = i % _col;
                int row = i / _col;
                float x =left + col * _aSize.x + ox;
                float y =top + row * -_aSize.y + oy;
                UpdateItem(i, x, y);
            }
        }
        void UpdateItem(int index,float x, float y)
        {
            if(index>=Items.Count)
            {
                Items.Add(CreateItem());
            }
            else
            {
                var i = Items[index];
                if (i.target.m_sizeDelta != _aSize)
                {
                    i.target.m_sizeDelta = _aSize;
                    UIAdaptive.Resize(i.target);
                }
            }
            var it = Items[index];
            it.index = index;
            it.datacontext = GetData(index);//dataList[index];
            it.target.localPosition.x = x;
            it.target.localPosition.y = y;
            //SetItemPostion(it, x, y);
            if (creator != null)
                creator.Call(it.obj, it.datacontext, index);
        }
        /// <summary>
        /// 创建项目实例
        /// </summary>
        /// <returns></returns>
        protected ScrollItem CreateItem()
        {
            ScrollItem a = new ScrollItem();
            if (creator != null)
            {
                if (creator.create)
                {
                    a.obj = creator.Create();
                    a.target = HGUIManager.Clone(ItemMod, creator.initializer);
                }
                else
                {
                    var go = HGUIManager.Clone(ItemMod);
                    a.obj = go;
                    a.target = go;
                }
            }
            else
            {
                var go = HGUIManager.Clone(ItemMod);
                a.obj = go;
                a.target = go;
            }
            a.target.SetParent(Enity);
            a.target.SetAsFirstSibling();
            a.target.localRotation = Quaternion.identity;
            a.target.localScale = Vector3.one;
            a.target.m_sizeDelta = _aSize;
            UIAdaptive.Resize(a.target);
            return a;
        }
        Constructor creator;
        /// <summary>
        /// 设置项目跟新函数
        /// </summary>
        /// <typeparam name="T">UI模板</typeparam>
        /// <typeparam name="U">数据模板</typeparam>
        /// <param name="action">项目更新回调</param>
        /// <param name="reflect">使用反射</param>
        public void SetItemUpdate<T, U>(Action<T, U, int> action, bool reflect = true) where T : class, new()
        {
            Clear();
            var m = new Middleware<T, U>();
            m.Invoke = action;
            creator = m;
            m.create = reflect;
        }
    }
}
